package top.javahai.chatroom.controller;

import com.nimbusds.jose.util.JSONObjectUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.StorageClient1;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.javahai.chatroom.entity.FIleSuess;
import top.javahai.chatroom.entity.FileList;
import top.javahai.chatroom.entity.RespBean;
import top.javahai.chatroom.utils.FastDFSUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author Overchat
 * @date 2021/9/21 - 16:47
 */
@Component
@RestController
public class FileController {
  @Value("${spring.hadoop.fsUri}")     private String urlPost;
  FileSystem fileSystem=null;
  @PostMapping("/file")
public List<FIleSuess>  uploadFlie(MultipartFile file, HttpServletRequest req) throws IOException, URISyntaxException, InterruptedException, MyException {
  SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
  String format = sdf.format(new Date());
  String realPath = req.getServletContext().getRealPath("/upload") + format;
  File folder = new File(realPath);
    System.out.println("----------------------------------***********************"+realPath);
  if (!folder.exists()) {
    folder.mkdirs();
  }
  String oldName = file.getOriginalFilename();
  String newName =oldName;
  file.transferTo(new File(folder,newName));
  String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/upload" + format + newName;
  System.out.println(url);
  String filePath=realPath+newName;
    System.out.println("fsfsfsfsfsf"+urlPost);
  fileSystem = FileSystem.get(new URI(urlPost), new Configuration(), "root");
    // 创建输入流，参数指定文件输出地址

    InputStream in = new FileInputStream(filePath);

    // 调用create方法指定文件上传，参数HDFS上传路径
    OutputStream out = fileSystem.create(new Path("/"+newName));
    // 使用Hadoop提供的IOUtils，将in的内容copy到out，设置buffSize大小，是否关闭流设置true
    IOUtils.copyBytes(in, out, 4096, true);
  System.out.println("文件路径"+filePath);
  System.out.println("real"+realPath);
  System.out.println(url);
    List<FIleSuess> map = new ArrayList<>();
    FIleSuess fIleSuess=new FIleSuess();

    fIleSuess.setFilename(newName);
    fIleSuess.setUrl(url);

    map.add(fIleSuess);


  return map;

}



  @DeleteMapping("/fileDelete/{filename}")
  public RespBean deletefile(@PathVariable String filename) throws IOException, URISyntaxException, InterruptedException {
    fileSystem = FileSystem.get(new URI(urlPost), new Configuration(), "root");
    if (fileSystem.delete(new Path("/"+filename), true)){
      return RespBean.ok("删除成功！");
    }
    else{
      return RespBean.error("删除失败！");
    }
  }

  @GetMapping("/fileList")
  public List<FileList>  listFile() throws IOException, URISyntaxException, InterruptedException {

    System.out.println("fsfsfsfsfsf"+urlPost);
    fileSystem = FileSystem.get(new URI(urlPost), new Configuration());
    FileStatus[] fileStatuses = fileSystem.listStatus(new Path("/"));

    List<FileList> fileLists= new ArrayList<>();
    List<String> list = new ArrayList<String>();
    for (FileStatus fileStatus : fileStatuses) {
      if(fileStatus.isDirectory()){
        Path path = fileStatus.getPath();
//                list.add(fileStatus.getPath().toString().substring(fileStatus.getPath().toString().lastIndexOf("/")));
      }else{
        FileList fileList = new FileList();
        Path path = fileStatus.getPath();
        String filename=fileStatus.getPath().toString().substring(fileStatus.getPath().toString().lastIndexOf("/"));
        fileList.setFilename(filename.substring(1,filename.length()));




        Long time = fileSystem.getFileStatus(path).getModificationTime(); //获取当前时间
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = format.format(time);//注意这里返回的是string类型
        fileList.setDate(date);

        fileLists.add(fileList);


      }


    }

//        for(String str:list){
//            FileList fileList = new FileList();
//            System.out.println("文件名字"+str);
//            fileList.setFilename(str);
//            fileList.setDate("2013");
//            fileLists.add(fileList);
//        }
    System.out.println("放到对象后的数据"+fileLists);
    return fileLists;
  }

  @PostMapping("/fileDowload/{filename}")
  public RespBean fileDowload(@PathVariable String filename) throws IOException, URISyntaxException, InterruptedException {
   fileSystem= FileSystem.get(new URI(urlPost), new Configuration(), "root");
    InputStream in = fileSystem.open(new Path("/"+filename));
    FileOutputStream out = new FileOutputStream(new File("d:/BigData/"+filename),true);
    IOUtils.copyBytes(in, out, 4096, true);
    File f = new File("D:/BigData/"+filename);

    if(f.exists()) {
      return RespBean.ok("下载成功！");
    }
    else{
      return RespBean.error("下载失败！");
    }

  }
}
